package com.k2data.k2app.service;

import com.k2data.app.kmx.KmxClient;
import com.k2data.app.kmx.cond.KmxCond;
import com.k2data.app.kmx.domain.Field;
import com.k2data.k2app.common.KmxParams;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.domain.po.TMonitorPoint;
import com.k2data.k2app.mapper.TMonitorVariableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lidong9144@163.com 17-7-13.
 */
@Service
public class KmxFieldService {

    private final TMonitorVariableMapper tMonitorVariableMapper;
    private final KmxParams kmxParams;
    @Autowired
    MyConstant myConstant;
    @Autowired
    public KmxFieldService(TMonitorVariableMapper tMonitorVariableMapper, KmxParams kmxParams) {
        this.tMonitorVariableMapper = tMonitorVariableMapper;
        this.kmxParams = kmxParams;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addField(TMonitorPoint point, List<Field> fields) {

        if (!fields.isEmpty()) {
            for (Field field : fields) {
                tMonitorVariableMapper.updateState(point.getId(), field.getName(), 1);
            }

            /*String[] ids = point.getNameEn().split("_");
            String id = ids[0]+"_"+ids[1];*/
            String fieldGroupId = myConstant.getFieldGroup(point.getNameEn());
            KmxCond kmxCond = KmxCond.fieldGroups(kmxParams.getKmxInitParams())
                    .addField()
                    .id(fieldGroupId)
                    .fields(fields)
                    .build();

            KmxClient.sync(kmxCond);
        }
    }

}
